//todo 如果要删除的文件正在上传（包括暂停），则需要发送给后端一个请求用来清除服务器端的缓存文件
(function () {
    var CommonUpload = function (url) {
        var that = this;
        this.maxSize = 500 * 1024 * 1024;
        this.chunkSize = 5000 * 1024;    //分块大小
        this.chunked = false;
        this.backEndUrl = url;
        this.fileInfo = {};
        this.uniqueFileName = null;     //文件唯一标识符
        this.md5Mark = null;
        this.progressContainer = "uploadProgress";
        this.auto = true;
        this.picker = "#picker";
        this.webUploader = null;
        this.fileQueued = function (file) {
            console.log(file);
        };
        this.uploadComplete = function (file) {
            console.log("complete");
        };
        this.uploadProgress = function (file, percentage) {
            var percent = parseInt(percentage * 100);
            layui.element.progress(that.progressContainer, percent + '%');
        };
        this.uploadError = function (file) {
            layer.msg("上传失败", {icon: 5});
        };
        this.uploadStart = function (file) {
            $("#" + that.progressContainer).removeClass("layui-hide");
        };
        this.uploadSuccess = function (file) {
            $("#" + that.progressContainer).addClass("layui-hide");
        };
    };

    CommonUpload.prototype = {
        init: function () {
            var that = this;
            if (that.chunked) {
                that.register();
            }
            that.webUploader = that.create();
            that.bindEvent(that.webUploader);
            return that.webUploader;
        },
        create: function () {
            var that = this;
            var uploader = WebUploader.create({
                // swf文件路径
                swf: '${basePath}/resources/zheng-admin/plugins/webuploader-0.1.5/Uploader.swf',
                server: that.backEndUrl,
                // 文件接收服务端
                method: 'POST',
                // 选择文件的按钮。可选。
                // 内部根据当前运行是创建，可能是input元素，也可能是flash.
                pick: {
                    "id": that.picker,
                    "multiple": false
                },
                // 不压缩image, 默认如果是jpeg，文件上传前会压缩一把再上传！
                resize: false,
                // 选完文件后，是否自动上传。

                prepareNextFile: true,
                chunked: that.chunked,
                chunkSize: that.chunkSize,
                threads: true,
                duplicate: true,
                auto: that.auto,
                formData: function () {
                    return $.extend(true, {}, that.fileInfo);
                }
            });
            return uploader;
        },
        register: function () {
            var that = this;
            WebUploader.Uploader.register({
                "before-send-file": "beforeSendFile",
                "before-send": "beforeSend",
                "after-send-file": "afterSendFile"
            }, {
                beforeSendFile: function (file) {
                    //秒传验证
                    var task = new $.Deferred();
                    (new WebUploader.Uploader()).md5File(file, 0, 10 * 1024 * 1024).then(function (val) {
                        that.md5Mark = val;
                        that.fileInfo.md5 = val;
                        $.ajax({
                            type: "POST",
                            url: that.backEndUrl,
                            data: {
                                status: "md5Check",
                                md5: val
                            },
                            cache: false,
                            timeout: 1000, //todo 超时的话，只能认为该文件不曾上传过
                            dataType: "json"
                        }).then(function (data, textStatus, jqXHR) {
                            if (data.data.ifExist) {   //若存在，这返回失败给WebUploader，表明该文件不需要上传
                                task.reject();
                                uploader.skipFile(file);
                                file.path = data.data.path;
                                that.uploadComplete(file);
                            } else {
                                task.resolve();
                                //拿到上传文件的唯一名称，用于断点续传
                                that.uniqueFileName = md5('' + that.fileInfo.userId + file.name + file.type + file.lastModifiedDate + file.size);
                            }
                        }, function (jqXHR, textStatus, errorThrown) {    //任何形式的验证失败，都触发重新上传
                            task.resolve();
                            //拿到上传文件的唯一名称，用于断点续传
                            that.uniqueFileName = md5('' + that.fileInfo.userId + file.name + file.type + file.lastModifiedDate + file.size);
                        });
                    });
                    return $.when(task);
                },
                beforeSend: function (block) {
                    //分片验证是否已传过，用于断点续传
                    var task = new $.Deferred();
                    $.ajax({
                        type: "POST",
                        url: that.backEndUrl,
                        data: {
                            status: "chunkCheck",
                            name: that.uniqueFileName,
                            chunkIndex: block.chunk,
                            size: block.end - block.start
                        },
                        cache: false,
                        timeout: 1000, //todo 超时的话，只能认为该分片未上传过
                        dataType: "json"
                    }).then(function (data, textStatus, jqXHR) {
                        if (data.data.ifExist) {   //若存在，返回失败给WebUploader，表明该分块不需要上传
                            task.reject();
                        } else {
                            task.resolve();
                        }
                    }, function (jqXHR, textStatus, errorThrown) {    //任何形式的验证失败，都触发重新上传
                        task.resolve();
                    });
                    return $.when(task);
                },
                afterSendFile: function (file) {
                    var chunksTotal = 0;
                    if ((chunksTotal = Math.ceil(file.size / that.chunkSize)) > 1) {
                        //合并请求
                        var task = new $.Deferred();
                        $.ajax({
                            type: "POST",
                            url: that.backEndUrl,
                            data: {
                                status: "chunksMerge",
                                name: that.uniqueFileName,
                                chunks: chunksTotal,
                                ext: file.ext,
                                md5: that.md5Mark
                            },
                            cache: false,
                            dataType: "json"
                        }).then(function (data, textStatus, jqXHR) {

                            //todo 检查响应是否正常

                            task.resolve();
                            file.path = data.data.path;
                            that.uploadComplete(file);

                        }, function (jqXHR, textStatus, errorThrown) {
                            task.reject();
                        });

                        return $.when(task);
                    } else {
                        that.uploadComplete(file);
                    }
                }
            });
        },
        bindEvent: function (bindObj) {
            var that = this;
            bindObj.on('uploadProgress', function (file, percentage) {
                that.uploadProgress(file, percentage);
            });
            bindObj.on('uploadError', function (file) {
                that.uploadError(file);
            });
            bindObj.on('uploadStart', function (file) {
                that.uploadStart(file);
            });
            bindObj.on('fileQueued', function (file) {
                that.fileQueued(file);
            });
            bindObj.on('uploadSuccess', function (file, response) {
                that.uploadSuccess(file, response);
            })
        },
        setProcessElement: function (val) {
            this.progressContainer = val;
        },
        setFileInfo: function (fileInfo) {
            this.fileInfo = fileInfo;
        },
        setChunked: function (chunked) {
            this.chunked = chunked;
        },
        setUploadProgress: function (func) {
            this.uploadProgress = func;
        },
        setUploadError: function (func) {
            this.uploadError = func;
        },
        setUploadComplete: function (func) {
            this.uploadComplete = func;
        },
        setUploadStart: function (func) {
            this.uploadStart = func;
        },
        setUploadSuccess: function (func) {
            this.uploadSuccess = func;
        },
        setFileQueued: function (func) {
            this.fileQueued = func;
        },
        setAuto: function (auto) {
            this.auto = auto;
        },
        setPicker: function (picker) {
            this.picker = picker;
        },
        startUpload: function () {
            //开始上传，非自动上传时触发这个
            this.webUploader.upload();
        }
    };
    window.CommonUpload = CommonUpload;


}());

